package com.whilelife.Wachovia.parser;

import com.whilelife.Wachovia.account.Account;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Brent Merle
 * Date: Nov 3, 2011
 * Time: 2:54:17 PM
 */
public class StatementReader {

  private static final HashMap<String, Account> accounts = new HashMap<String, Account>();
  private static final ArrayList<Integer> parsedFileHashes = new ArrayList<Integer>();
  private StatementReader() {
  }

  public static void parseStatements(List<String> files) throws IOException {
    for (String filePath : files) {

      PDDocument doc = null;
      try {
        PDFTextStripper stripper = new PDFTextStripper();
        doc = PDDocument.load(filePath);
        String text = stripper.getText(doc);
        if (parsedFileHashes.contains(text.hashCode())) {
          System.err.println("Already parsed " + filePath);
          continue;
        }
        String line;
        BufferedReader br = new BufferedReader(new StringReader(text));
        int statementYear = -1;
        while ((line = br.readLine()) != null) {

          line = line.trim();
          if (line.equalsIgnoreCase("Customer Service Information")) {
            break;
          } else if (line.startsWith("Account number")) {
            String number = line.substring(line.indexOf(':') + 1).trim();
            if (accounts.containsKey(number)) {
              accounts.get(number).parseData(br, statementYear);
            } else {
              Account acc = new Account(number);
              acc.parseData(br, statementYear);
              accounts.put(number, acc);
            }
          } else if (line.contains(" thru ")) {
            statementYear = Integer.parseInt(line.substring(line.lastIndexOf('/') + 1));
          }

        }
        parsedFileHashes.add(text.hashCode());
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (doc != null) {
          doc.close();
        }
      }
    }
    for (Account acc : accounts.values()) {
      System.out.println(acc);
    }
  }

  public static void reset() {
    accounts.clear();

    parsedFileHashes.clear();
  }

  public static String getCSVForAllAccounts() {
    StringBuilder sb = new StringBuilder("account#,date,amount,description");
    for (Account acc : accounts.values()) {
      sb.append('\n');
      sb.append(acc.toCSV());
    }
    return sb.toString();
  }


}
